﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Net.NetworkInformation;

namespace iTunesFastForward
{
    static class Utils
    {
        /// <summary>
        /// Submit a GET or POST request and returns the response as string
        /// </summary>
        /// <param name="uri">Standard URL</param>
        /// <param name="args">Arguments without the "?". Can be null</param>
        /// <param name="post">POST or not</param>
        /// <returns></returns>
        public static string SubmitRequestAndGetResponse(string uri, string args, bool post)
        {
            string userAgent = "Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.8.1.11) Gecko/20071127 Firefox/2.0.0.11"; // WINDOWS
            //string userAgent = "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.8.1.9) Gecko/20071110 Firefox/2.0.0.9"; // LINUX
            //string userAgent = "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)"; // GOOGLE BOT
            string referer = "http://www.google.com/";

            if (!post)
            {
                WebClient wc = new WebClient();
                wc.Headers[HttpRequestHeader.UserAgent] = userAgent;
                wc.Headers[HttpRequestHeader.Cookie] = "pass=deleted";


                try
                {
                    if (args == null)
                        return wc.DownloadString(uri);
                    else
                        return wc.DownloadString(uri + "?" + args);
                }
                catch (WebException)
                {
                    return null;
                }
            }
            else
            {
                try
                {
                    HttpWebRequest req = (HttpWebRequest)WebRequest.Create(uri);
                    req.Method = WebRequestMethods.Http.Post;
                    req.ContentType = "application/x-www-form-urlencoded";
                    // simuler firefox
                    req.Referer = referer;
                    req.UserAgent = userAgent;

                    byte[] bytes = Encoding.Default.GetBytes(args);
                    req.ContentLength = bytes.Length;

                    Stream reqStream = req.GetRequestStream();
                    reqStream.Write(bytes, 0, bytes.Length);
                    reqStream.Close();


                    WebResponse resp = req.GetResponse();

                    Stream newStream = resp.GetResponseStream();
                    StreamReader sr = new StreamReader(newStream);
                    string result = sr.ReadToEnd();
                    sr.Dispose();
                    newStream.Dispose();
                    return result;
                }
                catch (WebException)
                {
                    return null;
                }
            }
        }

        /// <summary>
        /// Submits a google "I'm feeling lucky" request, in order to directly go to the result page (usefull to avoid search results page)
        /// </summary>
        /// <param name="uri"></param>
        /// <returns></returns>
        public static string GoogleFeelingLuckyRequest(string uri)
        {
            string res = SubmitRequestAndGetResponse(uri, null, false);

            if (Regex.IsMatch(res, "Your search .* did not match any documents."))
                return null;
            else
                return res;
        }

        /// <summary>
        /// Shows a message with OK button and Error icon
        /// </summary>
        /// <param name="text">The text to display</param>
        /// <param name="title">The title (caption)</param>
        public static void ShowErrorMessage(string text, string title)
        {
            MessageBox.Show(text, title, MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

        //[DllImport(@"C:\Windows\System32\wininet.dll")]
        //private static extern bool InternetCheckConnection(string url, int flag, int ReservedValue);

        //public static bool IsConnectedToInternet { get; set; }

        //static Ping _pingSender;
        //static PingCompletedEventHandler _completed = new PingCompletedEventHandler(pingSender_PingCompleted);
        ///// <summary>
        ///// Checks if the computer is connected to internet
        ///// </summary>
        ///// <returns></returns>
        //public static void CheckInternetConnection(PingCompletedEventHandler del)
        //{
        //    if (_pingSender != null)
        //        return;
        //    else
        //        _pingSender = new Ping();

        //    if (del != null)
        //        _pingSender.PingCompleted += del;

        //    _pingSender.PingCompleted += _completed;

        //    // Create a buffer of 32 bytes of data to be transmitted.
        //    string data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
        //    byte[] buffer = Encoding.ASCII.GetBytes(data);

        //    // Wait 9 seconds for a reply.
        //    int timeout = 9000;

        //    // Set options for transmission:
        //    // The data can go through 64 gateways or routers
        //    // before it is destroyed, and the data packet
        //    // cannot be fragmented.
        //    PingOptions options = new PingOptions(64, true);

        //    // Send the ping asynchronously.
        //    // Use the waiter as the user token.
        //    // When the callback completes, it can wake up this thread.
        //    _pingSender.SendAsync("google.com", timeout, buffer, null);

        //}

        //static void pingSender_PingCompleted(object sender, PingCompletedEventArgs e)
        //{
        //    IsConnectedToInternet = !e.Cancelled && e.Error == null;
        //}

        /// <summary>
        /// Remove HTML Tags from a string
        /// </summary>
        /// <param name="strHTML"></param>
        /// <returns></returns>
        public static string ClearHTMLTags(string strHTML)
        {
            Regex regexp = new Regex("<[^>]*>", RegexOptions.IgnoreCase | RegexOptions.Singleline);
            return regexp.Replace(strHTML, string.Empty);
        }

    }
}
